package com.jushu.storbox.manager;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.jushu.storbox.callback.ITCallback;
import com.jushu.storbox.entities.UploadObject;
import com.jushu.storbox.task.tqueue.AlbumUploadTask;
import com.jushu.storbox.task.tqueue.UploadTaskScheduler;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;

public class AlbumUploadTaskManager {
	private static final int POOL_SIZE = 1;
	private final Set<AlbumUploadTask> uploadSet = new HashSet<AlbumUploadTask>();
	private final UploadTaskScheduler<AlbumUploadTask> uploadSequence = new UploadTaskScheduler<AlbumUploadTask>(POOL_SIZE);
	private static AlbumUploadTaskManager instance = null;
	
	private AlbumUploadTaskManager() {
	}
	
	public static AlbumUploadTaskManager instance() {
		if(instance == null) {
			instance = new AlbumUploadTaskManager();
		}
		return instance;
	}
	
	public void startScheduler() {
		uploadSequence.startScheduler();
	}
	public void stoptScheduler() {
		uploadSequence.stopScheduler();
	}
	public void startTaskExecuteService() {
		uploadSequence.startTaskExecuteService();
	}
	public void stopTaskExecuteService() {
		uploadSequence.stopTaskExecuteService();
	}
	
	public boolean addTask(AlbumUploadTask task) {
		synchronized (uploadSet) {
			if (uploadSet.add(task)) {
				uploadSequence.addTaskToScheduler(task);
				return true;//add success
			} else {
				return false;//add fail
			}
		}
	}
	
	public AlbumUploadTask getTask(String id) {
		AlbumUploadTask task = null;
		if(!uploadSet.isEmpty()) {
			for(Iterator<AlbumUploadTask> itor = uploadSet.iterator(); itor.hasNext();) {
				task = itor.next();
				if (id.equalsIgnoreCase(task.getId()))
					return task;
			}
		}
		return null;
	}
	
	public boolean removeTask(AlbumUploadTask task) {
		uploadSequence.removeTask(task);
		synchronized (uploadSet) {
			return uploadSet.remove(task);
		}
	}

	public Set<AlbumUploadTask> getAllTaskes() {
		return new HashSet<AlbumUploadTask>(uploadSet);
	}
	
	public void registerCallback(ITCallback<UploadObject, FileInfoResponseV2> callback) {
		synchronized (uploadSet) {
			for(AlbumUploadTask task : uploadSet) {
				task.setCallback(callback);
			}
		}
	}
	
	public void unRegisterCallback(ITCallback<UploadObject, FileInfoResponseV2> callback) {
		synchronized (uploadSet) {
			for(AlbumUploadTask task : uploadSet) {
				task.removeCallback(callback);
			}
		}
	}
	
	public Set<AlbumUploadTask> getAllTaskes(String folderID) {
		Set<AlbumUploadTask> tasks = new HashSet<AlbumUploadTask>();
		for(AlbumUploadTask task : uploadSet) {
			if (folderID.equalsIgnoreCase(task.getFolderID())) {
				tasks.add(task);
			}
		}
		return tasks;
	}
	
	public void stopAllTasks() {
		synchronized (uploadSet) {
			for(AlbumUploadTask task : uploadSet) {
				task.stopUploadTask();
			}
		}
		uploadSet.clear();
	}
}
